package cn.edu.hbvtc.qms.web.struts.action;

import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import cn.edu.hbvtc.qms.domain.Term;
import cn.edu.hbvtc.qms.domain.User;
import cn.edu.hbvtc.qms.service.IManagementService;

public class IndexAction extends AbstractBaseDispatchAction {

	private IManagementService managementService = null;

	public IManagementService getManagementService() {
		return managementService;
	}

	public void setManagementService(IManagementService managementService) {
		this.managementService = managementService;
	}

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Term termNow = managementService.findTermOfNow();
		
		Calendar c = Calendar.getInstance();
		c.setTime(new Date());
		
		if ((c.get(Calendar.YEAR) == termNow.getStartYear() + 1) && ((c.get(Calendar.MONTH) + 1 >= 2) && (c.get(Calendar.MONTH) + 1 <= 6))) {
			if (managementService.findTermByTimeAndOrder(termNow.getStartYear(), termNow.getEndYear(), 2) == null) {
				Term term = new Term();
				term.setStartYear(termNow.getStartYear());
				term.setEndYear(termNow.getEndYear());
				term.setTermOrder(2);
				
				managementService.saveTerm(term);
			}
		}
		
		if ((c.get(Calendar.YEAR) == termNow.getStartYear() + 1) && ((c.get(Calendar.MONTH) + 1 >= 8) && (c.get(Calendar.MONTH) + 1 <= 12))) {
			if (managementService.findTermByTimeAndOrder(termNow.getStartYear() + 1, termNow.getEndYear() + 1, 1) == null) {
				Term term = new Term();
				term.setStartYear(termNow.getStartYear() + 1);
				term.setEndYear(termNow.getEndYear() + 1);
				term.setTermOrder(1);
				
				managementService.saveTerm(term);
			}
		}
		
		//在用户信息页面显示最新学期信息
		Term termShow = managementService.findTermOfNow();
		
		HttpSession session = request.getSession();
		session.setAttribute("termShow", termShow);
		
		//获得当前登录用户信息
		User user = managementService.findUserByUsername(this.getPrincipal()
				.getUsername());
		session.setAttribute("nickname", user.getNickname());
		
		return mapping.findForward("index");
	}
	
}
